# coding:utf-8
'''
author:wangyi
'''

import tensorflow as tf
import pickle
import numpy as np
'''
1.create model structure(forward)
  1.1 var,shape
  1.2 unit h-param 
2.loss,opti (backward)
3.eval(MSE,MAPE)
4.predict/test
'''
# input_x = [[12.1,54.2,33.5,44.6,7.0]]
input_x = tf.placeholder(dtype=tf.float32,shape=[None,5,1])
# input_y = [[1]]
input_y = tf.placeholder(dtype=tf.float32,shape=[None,1])

#
cell = tf.nn.rnn_cell.GRUCell(num_units=10,dtype=tf.float32)
# return output [None,seq_len,num_units]
                # each [5,10]
output,state =tf.nn.dynamic_rnn(cell=cell,dtype=tf.float32,inputs=input_x)
# get final step output [None,1,10]
output = output[:,-1,:]

w = tf.Variable(initial_value=tf.truncated_normal(shape=[10,1],dtype=tf.float32))
b = tf.Variable(tf.constant([0],shape=[1],dtype=tf.float32))
# y = xw+b [None,1]
y_pred = tf.matmul(output,w)+b

## backward
loss = tf.reduce_mean(tf.square(y_pred-input_y))
opti = tf.train.GradientDescentOptimizer(learning_rate=1e-3).minimize(loss)

# create session
sess = tf.Session()
sess.run(tf.global_variables_initializer())

x_data,y_data = pickle.load(open('oil_data.pkl','rb'))
x_data = np.reshape(x_data,[-1,5,1])

with sess.as_default():
    for i in range(50):
        sess.run(opti,feed_dict={input_x:x_data,input_y:y_data})
        print(sess.run(loss,feed_dict={input_x:x_data,input_y:y_data}))